<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\Blog\Article;
use App\Models\Blog\Label;
use App\Models\Common\Category;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ArticleService
{
    use Service;

    /**
     * 分类
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ArticleCategoryService( $request )
    {
        $where    = function ( $query ) use ( $request ) {
            $query->where('is_show', 1);
            $query->where('status', 1);
            $query->where('parent_id', $request->input('parent_id', 0));
            $query->whereIn('static', [ 1, 3 ]);
        };
        $select   = [ 'id', 'name', 'parent_id', 'is_show', 'status', 'updated_at', 'static' ];
        $category = Category::GetModel($where, [], $select);
        unset($select, $where);
        $where  = function ( $query ) use ( $request ) {
            $query->where('status', 1);
            $query->where('is_show', 1);
            $query->where('static', 2);
        };
        $select = [ 'id', 'name', 'is_show', 'status', 'static', ];
        $label  = Label::AllModel($where, [], $select);
        if ( $request->ajax() ) return data($category);
        else return view('blog.article.create', compact('category', 'label'));
    }

    /**
     * 文章首页
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ArticleIndexService( $request )
    {
        $with    = [
            'user'         => function ( $query ) {
                $query->select('id', 'name');
            },
            'category'     => function ( $query ) {
                $query->select('id', 'name');
            },
            'parent'       => function ( $query ) {
                $query->select('id', 'name');
            },
            'articleLabel' => function ( $query ) {
                $query->select('id', 'name');
            },
            'file'         => function ( $query ) {
                $query->select('id', 'url');
            },
        ];
        $is_show = $request->input('is_show', 0);
        $name    = $request->input('name');
        $where   = function ( $query ) use ( $request, $is_show, $name ) {
            if ( $name ) $query->where('title', $name);
            if ( $is_show != 0 ) $query->where('is_show', $is_show);
            if ( $request->input('status', 0) != 0 ) $query->where('status', $request->input('status'));
            if ( $request->input('is', 0) != 0 ) $query->where('is', $request->input('is'));
            $query->where('static', 1);
        };
        $select  = [
            'id', 'user_id', 'category_id', 'parent_id', 'title', 'is_show', 'created_at', 'like', 'share',
            'browse', 'step', 'comment', 'root', 'static', 'status', 'fail', 'pic', 'is',
        ];
        $article = Article::PaginateModel($where, $with, $select);
        $article->appends([
            'name'    => $name,
            'is_show' => $is_show,
        ])->render();
        return view('blog.article.index', compact('article', 'request'));
    }

    /**
     * 获取详情
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ArticleEditService( $request )
    {
        $select         = [ 'id', 'title', 'category_id', 'parent_id', 'is_show', 'root', 'pic', 'is' ];
        $with           = [
            'content' => function ( $query ) {
                $query->select('article_id', 'markdown', 'intro', 'html');
            },
            'file'    => function ( $query ) {
                $query->select('id', 'url', 'file_url');
            },
        ];
        $article        = Article::FirstModel([ 'id' => $request->id ], $with, $select);
        $article->label = $article->articleLabel()->pluck('id')->toArray();
        unset($select);
        $where    = function ( $query ) use ( $request ) {
            $query->where('is_show', 1);
            $query->where('status', 1);
            $query->where('parent_id', 0);
        };
        $select   = [ 'id', 'name', 'parent_id', 'is_show', 'status', 'updated_at', 'static' ];
        $category = Category::GetModel($where, [], $select);
        unset($where, $select, $with);
        $where  = function ( $query ) use ( $request ) {
            $query->where('status', 1);
            $query->where('is_show', 1);
            $query->where('static', 2);
        };
        $select = [ 'id', 'name', 'is_show', 'status', 'static', ];
        $label  = Label::AllModel($where, [], $select);
        return view('blog.article.edit', compact('article', 'category', 'label'));
    }

    /**
     * 查看文章详情
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ArticleShowService( $id )
    {
        $select  = [ 'id', 'title' ];
        $with    = [
            'content' => function ( $query ) {
                $query->select('article_id', 'markdown', 'intro', 'html');
            },
        ];
        $article = Article::FirstModel([ 'id' => $id ], $with, $select);
        return view('blog.article.show', compact('article'));
    }


    /**
     * 新增
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ArticleStoreService( $request )
    {
        $validator = $this->getBlogValidator()->BlogArticleValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        $data[ 'user_id' ]     = Auth::id();
        $data[ 'title' ]       = $request->input('title');
        $data[ 'category_id' ] = $request->input('category_id', 0);
        $data[ 'pic' ]         = $request->input('pic');
        $data[ 'parent_id' ]   = $request->input('parent_id', 0);
        $data[ 'is_show' ]     = $request->input('is_show', 1);
        $data[ 'is' ]          = $request->input('is', 1);
        $data[ 'root' ]        = $request->input('root', 1);
        $data[ 'status' ]      = 3;
        DB::transaction(function () use ( $request, $data ) {
            $article = Article::CreateModel($data);
            unset($data);
            $data[ 'html' ]     = $request->input('html');
            $data[ 'markdown' ] = $request->input('markdown');
            $data[ 'intro' ]    = $request->input('intro');
            $tag                = [];
            if ( $request->filled('tag') ) $tag = explode(',', $request->input('tag'));
            $article->articleLabel()->sync($tag);
            $article->content()->create($data);
        });
        return back()->with('success', $this->getErrorCode()::message(209));
    }

    /**
     * 修改
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function ArticleUpdateService( $request )
    {
        $validator = $this->getBlogValidator()->BlogArticleValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        $data[ 'user_id' ]     = Auth::id();
        $data[ 'title' ]       = $request->input('title');
        $data[ 'category_id' ] = $request->input('category_id');
        $data[ 'pic' ]         = $request->input('pic');
        $data[ 'parent_id' ]   = $request->input('parent_id', 0);
        $data[ 'is_show' ]     = $request->input('is_show', 1);
        $data[ 'is' ]          = $request->input('is', 1);
        $data[ 'root' ]        = $request->input('root', 1);
        $data[ 'status' ]      = 3;
        DB::transaction(function () use ( $request, $data ) {
            $where   = function ( $query ) use ( $request ) {
                $query->where('id', $request->input('id'));
            };
            $select  = [ 'id', 'user_id', 'title', 'category_id', 'pic', 'parent_id', 'is_show', 'is', 'status' ];
            $article = Article::FirstModel($where, [], $select);
            $article->update($data);
            unset($data);
            $data[ 'html' ]     = $request->input('html');
            $data[ 'markdown' ] = $request->input('markdown');
            $data[ 'intro' ]    = $request->input('intro');
            $tag                = [];
            if ( $request->filled('tag') ) $tag = explode(',', $request->input('tag'));
            $article->articleLabel()->sync($tag);
            $article->content()->update($data);
        });
        return back()->with('success', $this->getErrorCode()::message(210));
    }

    /**
     * 文章 修改状态
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function ArticleStatusService( $id )
    {
        $article = Article::FindModel($id, [ 'id', 'is_show', 'status' ]);
        if ( $article->is_show == 1 ) $is_show = 2;
        else $is_show = 1;
        $article->is_show = $is_show;
        $article->save();
        return back()->with('success', $this->getErrorCode()::message(210));
    }

    /**
     * 博客文章删除
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function ArticleDestroyService( $id )
    {
        $article             = Article::FindModel($id, [ 'id', 'static', 'deleted_at' ]);
        $article->static     = 2;
        $article->deleted_at = Carbon::now()->toDateTimeString();
        $article->save();
        return back()->with('success', $this->getErrorCode()::message(204));
    }

    /**
     * 文章批量删除
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleDeleteService( $request )
    {
        $where = function ( $query ) use ( $request ) {
            $query->whereIn('id', $request->input('id'));
        };
        Article::UpdateModel($where, [
            'static'     => 2,
            'deleted_at' => Carbon::now()->toDateTimeString(),
        ]);
        return data();
    }

    /**
     * 文章 审核
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleExamineService( $request )
    {
        $error = $this->getErrorCode();
        if ( ! $article = Article::FindModel($request->input('id'), [
            'id', 'status', 'fail',
        ]) ) return message($error::message(2210));
        if ( $article->status != 2 ) return message($error::message(2210));
        $article->status = $request->input('status', 2);
        $article->fail   = $request->input('fail');
        $article->save();
        return data();
    }
}
